﻿using DevExpress.XtraGrid.Demos.util;
using DXApplicationTangche.DTO;
using DXApplicationTangche.service;
using DXApplicationTangche.UC.生产计划.生产批生产.service;
using DXApplicationTangche.UC.订单.service;
using DXApplicationTangche.UC.订单一览新.订单预览新.service;
using DXApplicationTangche.Utils;
using mendian;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DXApplicationTangche.UC.标签打印.Service
{
    public class 标签打印Service
    {
        public List<washDTO> washDTOs { get; set; }

        //根据生产批批号查询水洗标内容
        //反序列化，取数据
        public 标签打印Service(String batchNo)
        {
            this.washDTOs =
                    FunctionHelper.JsonDeserialization<List<washDTO>>(
                        RestCall.httpGetMethod(
                            URL.接口url + "/barcode/getWarterMarkPrintLogByBatchNo?batchNo=" + batchNo
                            )
                        );
            this.尺寸清洗();
        }

        /// <summary>
        /// 根据水洗生成水洗标打印信息
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static washDTO getWarterMarkPrintLogByBarcode(String barcode)
        {
            return
                FunctionHelper.JsonDeserialization<washDTO>(
                    RestCall.httpGetMethod(
                        URL.接口url + "/barcode/getWarterMarkPrintLogByBarcode?barcode=" + barcode
                        )
                    );
        }
        /// <summary>
        /// 根据门店返回打印模板一览
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public static PrintConfigDTO getPrintConfigByOrderId(String orderId)
        {
            return
                FunctionHelper.JsonDeserialization<PrintConfigDTO>(
                    RestCall.httpGetMethod(
                        URL.接口url + "/barcode/getPrintConfigByOrderId?orderId=" + orderId
                        )
                    );
        }
        /// <summary>
        /// 根据款式查询工信部质量标准
        /// </summary>
        /// <param name="styleNameCN"></param>
        /// <returns></returns>
        public static String getMIITStandardByStyleCode(String styleNameCN)
        {
            return
                RestCall.httpGetMethod(
                    URL.接口url + "/style/getMIITStandardByStyleCode?styleNameCN=" + styleNameCN
                    );
        }

        private void 尺寸清洗()
        {
            foreach (washDTO item in this.washDTOs)
            {
                try{ item.styleSizeCd = item.styleSizeCd.Replace("IGS_GROUP_SIZE-", "").Replace("EGS_GROUP_SIZE-", "");  }catch {}
            }
        }
        public static DTOTag get套号吊牌打印内容ByBarcode(String barcode)
        {
            //原来的打吊牌：打吊牌直接入库
            //return
            //    FunctionHelper.JsonDeserialization<DTOTag>(
            //        RestCall.httpGetMethod(
            //            URL.接口url + "/barcode/generateTagPrintByBarcode?barcode=" + barcode));

            //  新的仅打吊牌
            return
                FunctionHelper.JsonDeserialization<DTOTag>(
                    RestCall.httpGetMethod(
                        URL.接口url + "/barcode/generateTagPrintByBarcodeAfterCleaning?barcode=" + barcode));
        }
        /// <summary>
        /// 套号样品水洗打印
        /// </summary>
        /// <param name="washDTO">水洗信息</param>
        /// <param name="customerMade">是否定制，区分显示信息</param>
        /// <param name="printer">打印机名称</param>
        public static String print水洗(washDTO washDTO,bool customerMade,String printer)
        {
            //  判断打印模板文件名
            PrintConfigDTO printConfigDTO = 标签打印Service.getPrintConfigByOrderId(washDTO.orderId);
            //  正则表达式判断打印模板code128和code93
            String filePath;
            String templateMD5;
            if (Regex.Matches(washDTO.barcode, "[a-zA-Z]").Count > 0)
            {
                filePath = printConfigDTO.code128TemplateName;
                templateMD5 = printConfigDTO.code128TemplateMd5;
            }
            else
            {
                filePath = printConfigDTO.code93TemplateName;
                templateMD5 = printConfigDTO.code93TemplateMd5;
            }
            
            //  判断打印模板是否存在，不存在下载打印模板
            String fileName = Path.GetFileName(filePath);
            //String fileName = "WAIGOU_code93.btw";
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印

            try
            {
                if (!FileUtil.FileExist(@"tag\" + fileName))
                {
                    FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                }
                else
                {
                    //取文件MD5值
                    String FileMD5 = FileUtil.GetMD5HashFromFile(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);
                    //MD5值不为空
                    if (!String.IsNullOrEmpty(FileMD5))
                    {
                        //根据给的MD5值校验
                        //校验不同，模板不存在，下载打印模板
                        if (!FileMD5.Equals(templateMD5))
                        {
                            File.Delete(@"tag\" + fileName);
                            FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("打印模板下载失败");
            }
            //打印机配置文件filePath
            Engine btEngine = new Engine();
            btEngine.Start();
            LabelFormatDocument btFormat = btEngine.Documents.Open(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);
            
            btFormat.PrintSetup.PrinterName = printer;
            //btFormat.PrintSetup.PrinterName = "HPRT HLP106S-UE";
            //btFormat.PrintSetup.PrinterName = "迅捷PDF虚拟打印机";
            //btFormat.PrintSetup.PrinterName = "TEC B-462-R";
            //btFormat.PrintSetup.PrinterName = " Microsoft Print to PDF";
            //btFormat.PrintSetup.PrinterName = "PDFCreator";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 

            //赋值的时候因为现在是List 不是单个对象，要把这一行的数赋值给gridView，所以用e.RowHandle
            if (customerMade)
            {

                try
                {
                    btFormat.SubStrings["orderNo"].Value = washDTO.orderNo;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["customerName"].Value = washDTO.customerName;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["fabricNumber"].Value = washDTO.materialCode;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["fabricComposition"].Value = washDTO.composition;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["barCode"].Value = washDTO.barcode;
                }
                catch { }

            }
            else {

                try
                {
                    btFormat.SubStrings["styleNameCn"].Value = washDTO.styleNameCn;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["styleSizeCd"].Value = washDTO.styleSizeCd;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["fabricNumber"].Value = washDTO.materialCode;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["fabricComposition"].Value = washDTO.composition;
                }
                catch { }
                try
                {
                    btFormat.SubStrings["barCode"].Value = washDTO.barcode;
                }
                catch { }
            }
            //btFormat.SubStrings["standard"].Value = this.standard;
            String standard;
            try
            {
                //  根据款式查询工信部质量标准
                String styleNameCn = washDTO.styleNameCn;
                standard = 标签打印Service.getMIITStandardByStyleCode(styleNameCn);
            }
            catch
            {
                standard = "FZ/T 73020-2019";
            }

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Seagull.BarTender.Print.Result nResult1 = btFormat.Print("套号水洗标" + "", waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
            return nResult1.ToString();
        }
        //测试
        public static String print水洗(外购DTO dTOTag, bool customerMade, String printer)
        {
            //  判断打印模板文件名
            //PrintConfigDTO printConfigDTO = 标签打印Service.getPrintConfigByOrderId(dTOTag.orderId);
            //  正则表达式判断打印模板code128和code93
            String filePath;
            String templateMD5;
            filePath = "WAIGOU_code93.btw";
            //templateMD5 = printConfigDTO.code93TemplateMd5;

            //  判断打印模板是否存在，不存在下载打印模板
            //String fileName = Path.GetFileName(filePath);
            String fileName = "WAIGOU_code93.btw";
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印

            try
            {
                if (!FileUtil.FileExist(@"tag\" + fileName))
                {
                    FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                }
                else
                {
                    //取文件MD5值
                    String FileMD5 = FileUtil.GetMD5HashFromFile(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);
                    //MD5值不为空
                    if (!String.IsNullOrEmpty(FileMD5))
                    {
                        FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                        //根据给的MD5值校验
                        //校验不同，模板不存在，下载打印模板
                        //if (!FileMD5.Equals(templateMD5))
                        //{
                        //    File.Delete(@"tag\" + fileName);
                        //    FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("打印模板下载失败");
            }
            //打印机配置文件filePath
            Engine btEngine = new Engine();
            btEngine.Start();
            LabelFormatDocument btFormat = btEngine.Documents.Open(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);

            btFormat.PrintSetup.PrinterName = printer;
            //btFormat.PrintSetup.PrinterName = "HPRT HLP106S-UE";
            //btFormat.PrintSetup.PrinterName = "迅捷PDF虚拟打印机";
            //btFormat.PrintSetup.PrinterName = "TEC B-462-R";
            //btFormat.PrintSetup.PrinterName = " Microsoft Print to PDF";
            //btFormat.PrintSetup.PrinterName = "PDFCreator";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 

            //赋值的时候因为现在是List 不是单个对象，要把这一行的数赋值给gridView，所以用e.RowHandle
            if (customerMade)
            {
                //btFormat.SubStrings["orderNo"].Value = dTOTag.orderNo;
                //btFormat.SubStrings["customerName"].Value = dTOTag.customerName;
                //btFormat.SubStrings["fabricNumber"].Value = dTOTag.materialCode;
                //btFormat.SubStrings["fabricComposition"].Value = washDTO.composition;
                //btFormat.SubStrings["barCode"].Value = washDTO.barcode;
            }
            else
            {
                btFormat.SubStrings["styleNameCn"].Value = "款式 "+dTOTag.styleNameCn;
                btFormat.SubStrings["styleSizeCd"].Value = "尺码 "+dTOTag.styleSizeCd.Replace("IGS_GROUP_SIZE-", "");
                btFormat.SubStrings["barCode"].Value = dTOTag.inventoryNo;
            }
            //btFormat.SubStrings["standard"].Value = this.standard;
            String standard;
            try
            {
                //  根据款式查询工信部质量标准
                String styleNameCn = dTOTag.styleNameCn;
                standard = 标签打印Service.getMIITStandardByStyleCode(styleNameCn);
            }
            catch
            {
                standard = "FZ/T 73020-2019";
            }

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Seagull.BarTender.Print.Result nResult1 = btFormat.Print("套号水洗标" + "", waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
            return nResult1.ToString();
        }
        public static void print套号水洗(washDTO washDTO, bool customerMade)
        {
            //  判断打印模板文件名
            PrintConfigDTO printConfigDTO = 标签打印Service.getPrintConfigByOrderId(washDTO.orderId);
            //  正则表达式判断打印模板code128和code93
            String filePath;
            String templateMD5;
            if (Regex.Matches(washDTO.barcode, "[a-zA-Z]").Count > 0)
            {
                filePath = printConfigDTO.code128TemplateName;
                templateMD5 = printConfigDTO.code128TemplateMd5;
            }
            else
            {
                filePath = printConfigDTO.code93TemplateName;
                templateMD5 = printConfigDTO.code93TemplateMd5;
            }

            //  判断打印模板是否存在，不存在下载打印模板
            String fileName = Path.GetFileName(filePath);
            //根据相对路径判断模板是否存在
            //不存在则下载进行打印

            try
            {
                if (!FileUtil.FileExist(@"tag\" + fileName))
                {
                    FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                }
                else
                {
                    //取文件MD5值
                    String FileMD5 = FileUtil.GetMD5HashFromFile(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);
                    //MD5值不为空
                    if (!String.IsNullOrEmpty(FileMD5))
                    {
                        //根据给的MD5值校验
                        //校验不同，模板不存在，下载打印模板
                        if (!FileMD5.Equals(templateMD5))
                        {
                            FileUtil.DownloadPicture(URL.图片url + URL.套号模板路径 + filePath, @"tag\" + fileName, -1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("打印模板下载失败");
            }
            //打印机配置文件filePath
            Engine btEngine = new Engine();
            btEngine.Start();
            LabelFormatDocument btFormat = btEngine.Documents.Open(System.AppDomain.CurrentDomain.BaseDirectory + @"tag\" + fileName);

            //btFormat.PrintSetup.PrinterName = "HPRT HLP106S-UE";
            //btFormat.PrintSetup.PrinterName = "迅捷PDF虚拟打印机";
            btFormat.PrintSetup.PrinterName = "TEC B-462-R";
            //btFormat.PrintSetup.PrinterName = " Microsoft Print to PDF";
            //btFormat.PrintSetup.PrinterName = "PDFCreator";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 1;
            //对BTW模版相应字段进行赋值 

            //赋值的时候因为现在是List 不是单个对象，要把这一行的数赋值给gridView，所以用e.RowHandle
            if (customerMade)
            {
                btFormat.SubStrings["orderNo"].Value = washDTO.orderNo;
                btFormat.SubStrings["customerName"].Value = washDTO.customerName;
                btFormat.SubStrings["fabricNumber"].Value = washDTO.materialCode;
                btFormat.SubStrings["fabricComposition"].Value = washDTO.composition;
                btFormat.SubStrings["barCode"].Value = washDTO.barcode;
            }
            else
            {
                btFormat.SubStrings["styleNameCn"].Value = washDTO.styleNameCn;
                btFormat.SubStrings["styleSizeCd"].Value = washDTO.styleSizeCd;
                btFormat.SubStrings["fabricNumber"].Value = washDTO.materialCode;
                btFormat.SubStrings["fabricComposition"].Value = washDTO.composition;
                btFormat.SubStrings["barCode"].Value = washDTO.barcode;
            }
            //btFormat.SubStrings["standard"].Value = this.standard;
            String standard;
            try
            {
                //  根据款式查询工信部质量标准
                String styleNameCn = washDTO.styleNameCn;
                standard = 标签打印Service.getMIITStandardByStyleCode(styleNameCn);
            }
            catch
            {
                standard = "FZ/T 73020-2019";
            }

            Messages messages;
            int waitout = 10000; // 10秒 超时 
            Seagull.BarTender.Print.Result nResult1 = btFormat.Print("套号水洗标" + "", waitout, out messages);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
        }

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        /// <summary>
        /// 上传打印文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="md5"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String uploadPrintFile(OpenFileDialog ofd)
        {
            String fileNameCn = Path.GetFileName(ofd.FileName);
            String fileName = FileUtil.getFileName(fileNameCn);
            String md5 = FileUtil.GetMD5HashFromFile(ofd.FileName);
            return
                FileService.UploadRequest(
                    URL.接口url + "/barcode/uploadPrintFile?fileName=" + fileName
                        + "&md5=" + md5,
                    ofd.FileName,
                    Path.GetFileName(ofd.FileName),
                    "multipartFile"
                    );
        }
        //DTOTag
        /// <summary>
        /// 
        /// </summary>
        /// <param name="styleNameCn"></param>
        /// <param name="styleSizeCd"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public static List<外购DTO> getGarmentTagPrintList(String styleNameCn, String styleSizeCd, int quantity)
        {
            return
                FunctionHelper.JsonDeserialization<List<外购DTO>>(
                    RestCall.httpGetMethod(
                        URL.接口url + "/barcode/getGarmentTagPrintList?styleNameCn=" + styleNameCn
                                                                    + "&styleSizeCd=" + styleSizeCd
                                                                    + "&quantity=" + quantity));
        }
        //PlainMessageResult
        /// <summary>
        /// 
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static PlainMessageResult purchaseGarmentStockInOut(String barcode,int inOutFlag,String shopId)
        {
            return
                FunctionHelper.JsonDeserialization<PlainMessageResult>(
                    RestCall.httpGetMethod(
                        URL.接口url + "/store/purchaseGarmentStockInOut?barcode=" + barcode
                                                                    + "&inOutFlag=" + inOutFlag
                                                                    + "&shopId=" + shopId
                        )
                    );
        }
    }

    public class washDTO {
        public String batchNo { get; set; } //  生产批批号
        public String orderId { get; set; } //  订单id
        public String orderNo { get; set; } //  订单号
        public String customerName { get; set; }   //  客户名
        public String materialCode { get; set; }   //  面料编码
        public String composition { get; set; } //  成分
        public String barcode { get; set; }//  条码
        public String styleNameCn { get; set; }//  款式名称
        public String styleSizeCd { get; set; }//尺码
        public washDTO()
        {

        }
    }
    public class 外购DTO
    {
        public int orderNumber { get; set; } //  
        public String styleNameCn { get; set; } //  
        public String styleSizeCd { get; set; } //  
        public String inventoryNo { get; set; }   //  
        public Boolean mtoInventory { get; set; }   //  
        public 外购DTO()
        {

        }
    }
    public class DTOTag
    {
        public String batchNo { get; set; } //批号
        public List<String> inventoryNos { get; set; } = new List<string>();   //条形码
        public String materialCode { get; set; }  //面料号
        public String materialComposition { get; set; }   //面料成分
        public List<MeasureItemDTO> measureItemDTOS { get; set; } = new List<MeasureItemDTO>();
        public String orderId { get; set; } //订单Id
        public String orderNumber { get; set; }//订单号
        public String styleId { get; set; }  //款式Id
        public String styleNameCn { get; set; }   //款名
        public String styleSizeCd { get; set; }    //尺码
        public String sytleFabricId { get; set; }   //面料Id
        public String styleCategoryCd { get; set; } //款式类别
        public double price { get; set; }//价格
        public Boolean mtoInventory{ get; set; }  //  是否MTO库存
        public String customerName { get; set; }   //  客户姓名
        public DTOTag()
        {

        }
    }
    public class DTO套号吊牌尺寸
    {
        public String 吊牌项目 { get; set; }//数据源
        public String 成衣值 { get; set; }//
        public DTO套号吊牌尺寸(string 吊牌项目, string 成衣值)
        {
            this.吊牌项目 = 吊牌项目;
            this.成衣值 = 成衣值;
        }

    }
    public class PrintConfigDTO
    {
        public String shopId { get; set; }//
        public String code93TemplateName { get; set; }//
        public String code128TemplateName { get; set; }//
        public String code93TemplateMd5 { get; set; }//
        public String code128TemplateMd5 { get; set; }//
        public PrintConfigDTO()
        {

        }

    }
    public class PrintMachineDTO
    {
        public String id { get; set; }//
        public String printName { get; set; }//
        public PrintMachineDTO()
        {

        }

        public PrintMachineDTO(string id, string printName)
        {
            this.id = id;
            this.printName = printName;
        }
    }
}
